// app/service/lock.js
'use strict';

const { Service } = require('egg');

class LockService extends Service {
  async withLock(key, ttl, func) {
    const { app } = this.ctx;
    const lockKey = `lock:${key}`;
    let renewalTimer;

    try {
      // 获取分布式锁
      const acquired = await app.redis.set(lockKey, '1', 'EX', ttl, 'NX');
      if (!acquired) throw new Error('获取锁失败');

      // 启动自动续期
      renewalTimer = setInterval(async () => {
        await app.redis.expire(lockKey, ttl);
      }, ttl * 1000 * 0.8); // 在80% TTL时续期

      return await func();
    } finally {
      clearInterval(renewalTimer);
      await app.redis.del(lockKey);
    }
  }
}

module.exports = LockService;